<template>
  <div class="api-demo-container p-4 border rounded-md shadow-sm">
    <h2 class="text-xl font-bold mb-4">API调用示例</h2>

    <div class="mb-6">
      <h3 class="text-lg font-semibold mb-2">用户登录</h3>
      <div class="flex flex-col space-y-2 max-w-md">
        <input
          v-model="username"
          placeholder="用户名"
          class="px-3 py-2 border rounded-md"
        />
        <input
          v-model="password"
          type="password"
          placeholder="密码"
          class="px-3 py-2 border rounded-md"
        />
        <button
          @click="handleLogin"
          class="px-4 py-2 bg-primary text-white rounded-md hover:bg-primary/90 transition-colors"
        >
          登录
        </button>
      </div>
      <div v-if="userInfo" class="mt-4 p-3 bg-gray-100 rounded-md">
        <h4 class="font-medium mb-1">用户信息:</h4>
        <pre>{{ userInfo }}</pre>
      </div>
    </div>

    <div>
      <h3 class="text-lg font-semibold mb-2">产品列表</h3>
      <button
        @click="getProducts"
        class="px-4 py-2 bg-secondary text-white rounded-md hover:bg-secondary/90 transition-colors mb-4"
      >
        获取产品列表
      </button>
      <div v-if="products.length > 0" class="space-y-3">
        <div
          v-for="product in products"
          :key="product.id"
          class="p-3 border rounded-md"
        >
          <h4 class="font-medium">{{ product.name }}</h4>
          <p class="text-gray-600">价格: ¥{{ product.price }}</p>
          <p v-if="product.description" class="text-sm text-gray-500">
            {{ product.description }}
          </p>
        </div>
      </div>
      <p v-else-if="products.length === 0">暂无产品数据</p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { userApi, productApi } from '@/api'

const username = ref('')
const password = ref('')
const userInfo = ref<any>(null)
const products = ref<any[]>([])
const loading = ref(false)

// 处理登录
const handleLogin = async () => {
  if (!username.value || !password.value) {
    alert('请输入用户名和密码')
    return
  }

  loading.value = true
  try {
    const res = await userApi.login({
      username: username.value,
      password: password.value
    })
    userInfo.value = res.data
    alert('登录成功')
  } catch (error) {
    console.error('登录失败:', error)
    alert('登录失败，请重试')
  } finally {
    loading.value = false
  }
}

// 获取产品列表
const getProducts = async () => {
  loading.value = true
  try {
    const res = await productApi.getProductList({
      page: 1,
      pageSize: 10
    })
    products.value = res.data || []
  } catch (error) {
    console.error('获取产品列表失败:', error)
    alert('获取产品列表失败，请重试')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.api-demo-container {
  max-width: 800px;
  margin: 0 auto;
}

pre {
  white-space: pre-wrap;
  word-break: break-all;
}
</style>
